const crypto = require('crypto');
const axios = require('axios');
/**
 * 将参数进行签名
 * @param {object} params 待签名数据结构
 * @param {string} appSecret 签名key
 */
module.exports.createSign = (params, appSecret) => {
	const paramKeys = Object.keys(params).sort();
	let signStr = '';
	paramKeys.forEach(key => {
		let value = params[key];
		// 空值，risk_info不参与签名
		if (!value || ['risk_info'].indexOf(key) >= 0) {
			return;
		}
		if (signStr.length > 0) {
			signStr += '&';
		}
		if (typeof value === 'object') {
			value = JSON.stringify(value);
		}
		signStr += key + '=' + value;
	});
	signStr += `${appSecret}`;
	console.log('signStr:', signStr);
	const md5 = crypto.createHash('md5');
	const sign = md5.update(signStr).digest('hex');
	return sign;
};

/**
 * 下划线转驼峰
 * @param {*} name
 */
module.exports.toHump = name => {
	return name.replace(/\_(\w)/g, function(all, letter) {
		return letter.toUpperCase();
	});
};

/**
 * 	驼峰转下划线
 * @param {*} name
 */
module.exports.toLine = name => {
	return name.replace(/([A-Z])/g, '_$1').toLowerCase();
};

module.exports.axiosFormData = async params => {
	if (typeof params == 'object') {
		params = seriealizeParams(params);
	}

	const result = await axios
		.post(`https://tp-pay.snssdk.com/gateway`, params, {
			headers: { devinfo: '', Cookie: '', 'User-Agent': '' },
		})
		.catch(e => {
			console.log(e);
			return {
				response: {
					code: 999,
					msg: '网络异常',
				},
			};
		});

	return result.data || {};
};

function seriealizeParams(data = {}) {
	let params = [];
	Object.keys(data).forEach(key => {
		if (typeof data[key] == 'object') {
			params.push(key + '=' + encodeURIComponent(JSON.stringify(data[key])));
		} else {
			params.push(key + '=' + encodeURIComponent(data[key]));
		}
	});

	return params.join('&');
}
